package com.company.jrlz.service;

import com.company.jrlz.entity.ExtFileDescriptor;
import com.haulmont.bali.util.URLEncodeUtils;
import com.haulmont.cuba.core.entity.FileDescriptor;
import com.haulmont.cuba.core.global.*;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.inject.Inject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service(BaseService.NAME)
public class BaseServiceBean implements BaseService {

    @Inject
    private DataManager dataManager;

    @Inject
    private FileLoader fileLoader;


    @Override
    public Map lastVersionsFile() {
        Map<String, Object> map = new HashedMap<>();
        LoadContext<FileDescriptor> loadContext = LoadContext.create(FileDescriptor.class)
                .setQuery(
                        LoadContext.createQuery("select e from sys$FileDescriptor e " +
                                "order by e.createTs desc")
                );
        List<FileDescriptor> fileDescriptors = dataManager.loadList(loadContext);
        if (fileDescriptors != null) {
            if (fileDescriptors.size() != 0) {
                ExtFileDescriptor extFile = (ExtFileDescriptor) fileDescriptors.get(0);
                map.put("uuid", extFile.getId());
                map.put("name", extFile.getName());
                map.put("versions", extFile.getVersions());
            }
        }
        return map;
    }

    @Override
    public void downloadFile(String uuid) {
        FileDescriptor extFile = dataManager.load(FileDescriptor.class).id(UUID.fromString(uuid)).one();
        try {
            InputStream inputStream = fileLoader.openStream(extFile);
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletResponse response = requestAttributes.getResponse();
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-Type", FileTypesHelper.getMIMEType("." + extFile.getExtension().toLowerCase()));
            response.setHeader("Content-Disposition", ("attachment")
                    + "; filename=\"" + URLEncodeUtils.encodeUtf8(extFile.getName()) + "\"");

            ServletOutputStream os = response.getOutputStream();
            IOUtils.copy(inputStream, os);
            os.flush();
        } catch (FileStorageException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}